<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>五子棋在线对战 - 游戏房间</title>
    <link rel="stylesheet" href="common.css">
    <style>
        body {
            background: #f8f9fa;
            margin: 0;
            font-family: 'Microsoft YaHei', Arial, sans-serif;
        }
        
        .header {
            background: #2c3e50;
            color: white;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .header h1 {
            font-size: 18px;
            font-weight: bold;
        }
        
        .game-info {
            display: flex;
            align-items: center;
            gap: 20px;
        }
        
        .player-info {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 8px 15px;
            border-radius: 20px;
            background: rgba(255,255,255,0.1);
        }
        
        .player-info.current-turn {
            background: #e67e22;
            animation: pulse 2s infinite;
        }
        
        .player-avatar {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 12px;
        }
        
        .player-avatar.black {
            background: #000;
        }
        
        .player-avatar.white {
            background: #fff;
            color: #000;
        }
        
        .player-details {
            display: flex;
            flex-direction: column;
        }
        
        .player-name {
            font-weight: bold;
            font-size: 12px;
        }
        
        .player-score {
            font-size: 10px;
            opacity: 0.8;
        }
        
        .turn-indicator {
            font-size: 14px;
            font-weight: bold;
            color: #f39c12;
        }
        
        .back-btn {
            background: #e74c3c;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }
        
        .back-btn:hover {
            background: #c0392b;
        }
        
        .main-container {
            display: flex;
            min-height: calc(100vh - 70px);
            padding: 20px;
            gap: 20px;
        }
        
        .board-container {
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .board {
            width: 600px;
            height: 600px;
            background: #f5f5dc;
            border: 3px solid #8b4513;
            border-radius: 8px;
            position: relative;
            display: grid;
            grid-template-columns: repeat(15, 1fr);
            grid-template-rows: repeat(15, 1fr);
            gap: 0;
        }
        
        .board-cell {
            border: 1px solid #8b4513;
            position: relative;
            cursor: pointer;
            transition: background-color 0.2s ease;
        }
        
        .board-cell:hover {
            background-color: rgba(52, 152, 219, 0.2);
        }
        
        .board-cell.occupied {
            cursor: not-allowed;
        }
        
        .board-cell.occupied:hover {
            background-color: transparent;
        }
        
        .piece {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 32px;
            height: 32px;
            border-radius: 50%;
            border: 2px solid #333;
            animation: dropIn 0.3s ease-out;
        }
        
        .piece.black {
            background: #000;
        }
        
        .piece.white {
            background: #fff;
        }
        
        .piece.last-move {
            border: 3px solid #e74c3c;
            box-shadow: 0 0 10px rgba(231, 76, 60, 0.5);
        }
        
        .piece.winning {
            border: 3px solid #ffd700;
            box-shadow: 0 0 15px rgba(255, 215, 0, 0.8);
            animation: winGlow 1s infinite alternate;
        }
        
        .control-panel {
            width: 300px;
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
            height: fit-content;
        }
        
        .timer-section {
            margin-bottom: 30px;
        }
        
        .timer-title {
            color: #2c3e50;
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 15px;
        }
        
        .timer-display {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
        }
        
        .timer-item {
            text-align: center;
            padding: 10px;
            border-radius: 8px;
            background: #f8f9fa;
        }
        
        .timer-item.active {
            background: #e67e22;
            color: white;
        }
        
        .timer-label {
            font-size: 12px;
            margin-bottom: 5px;
        }
        
        .timer-value {
            font-size: 18px;
            font-weight: bold;
        }
        
        .game-controls {
            margin-bottom: 30px;
        }
        
        .undo-btn {
            width: 100%;
            background: #95a5a6;
            color: white;
            border: none;
            padding: 15px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .undo-btn:hover:not(:disabled) {
            background: #7f8c8d;
            transform: translateY(-2px);
        }
        
        .undo-btn:disabled {
            background: #bdc3c7;
            cursor: not-allowed;
            opacity: 0.6;
        }
        
        .surrender-btn {
            width: 100%;
            background: #e74c3c;
            color: white;
            border: none;
            padding: 15px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .surrender-btn:hover {
            background: #c0392b;
            transform: translateY(-2px);
        }
        
        .game-rules {
            margin-bottom: 30px;
        }
        
        .rules-title {
            color: #2c3e50;
            font-size: 14px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        
        .rules-content {
            font-size: 12px;
            color: #7f8c8d;
            line-height: 1.5;
        }
        
        .score-preview {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
        }
        
        .score-title {
            color: #2c3e50;
            font-size: 14px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        
        .score-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
            font-size: 12px;
        }
        
        .score-positive {
            color: #27ae60;
            font-weight: bold;
        }
        
        .score-negative {
            color: #e74c3c;
            font-weight: bold;
        }
        
        .reconnect-status {
            background: #e67e22;
            color: white;
            padding: 10px;
            border-radius: 6px;
            text-align: center;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }
        
        .reconnect-spinner {
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255,255,255,0.3);
            border-top-color: white;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .timer-item.warning {
            background: #e74c3c !important;
            color: white;
            animation: pulse 1s infinite;
        }
        
        .game-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        
        .game-overlay.show {
            display: flex;
        }
        
        .game-result {
            background: white;
            padding: 40px;
            border-radius: 12px;
            text-align: center;
            max-width: 400px;
            width: 90%;
        }
        
        .result-title {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 20px;
        }
        
        .result-win {
            color: #27ae60;
        }
        
        .result-lose {
            color: #e74c3c;
        }
        
        .result-draw {
            color: #f39c12;
        }
        
        .result-message {
            font-size: 16px;
            margin-bottom: 20px;
            color: #2c3e50;
        }
        
        .score-change {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 30px;
        }
        
        .score-change-title {
            font-size: 14px;
            font-weight: bold;
            margin-bottom: 10px;
            color: #2c3e50;
        }
        
        .score-change-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
        }
        
        .back-to-lobby-btn {
            background: #3498db;
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .back-to-lobby-btn:hover {
            background: #2980b9;
            transform: translateY(-2px);
        }
        
        @keyframes dropIn {
            from {
                transform: translate(-50%, -50%) scale(0);
                opacity: 0;
            }
            to {
                transform: translate(-50%, -50%) scale(1);
                opacity: 1;
            }
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        
        @keyframes winGlow {
            from { box-shadow: 0 0 15px rgba(255, 215, 0, 0.8); }
            to { box-shadow: 0 0 25px rgba(255, 215, 0, 1); }
        }
        
        @media (max-width: 1023px) and (min-width: 768px) {
            /* 平板端布局 */
            .main-container {
                flex-direction: column;
                padding: 15px;
                gap: 15px;
            }
            
            .board-container {
                order: 1;
            }
            
            .board {
                width: 500px;
                height: 500px;
            }
            
            .piece {
                width: 28px;
                height: 28px;
            }
            
            .control-panel {
                width: 100%;
                order: 2;
                display: flex;
                flex-direction: row;
                gap: 20px;
                height: auto;
            }
            
            .timer-section, .game-controls, .game-rules, .score-preview {
                flex: 1;
            }
        }
        
        @media (max-width: 767px) {
            /* 移动端布局 */
            .main-container {
                flex-direction: column;
                padding: 10px;
            }
            
            .board {
                width: 400px;
                height: 400px;
            }
            
            .piece {
                width: 24px;
                height: 24px;
            }
            
            .control-panel {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>五子棋对战</h1>
        <div class="game-info">
            <div class="player-info" id="blackPlayer">
                <div class="player-avatar black">黑</div>
                <div class="player-details">
                    <div class="player-name" id="blackPlayerName">玩家001</div>
                    <div class="player-score">积分: 150</div>
                </div>
            </div>
            <div class="turn-indicator" id="turnIndicator">轮到黑方</div>
            <div class="player-info" id="whitePlayer">
                <div class="player-avatar white">白</div>
                <div class="player-details">
                    <div class="player-name" id="whitePlayerName">玩家002</div>
                    <div class="player-score">积分: 145</div>
                </div>
            </div>
            <button class="back-btn" onclick="backToLobby()">返回大厅</button>
        </div>
    </div>
    
    <div class="main-container">
        <div class="board-container">
            <div class="board" id="gameBoard">
                <!-- 棋盘格子将通过JavaScript动态生成 -->
            </div>
        </div>
        
        <div class="control-panel">
            <div class="timer-section">
                <div class="timer-title">游戏计时</div>
                <div class="timer-display">
                    <div class="timer-item" id="blackTimer">
                        <div class="timer-label">黑方</div>
                        <div class="timer-value" id="blackTime">00:00</div>
                    </div>
                    <div class="timer-item" id="whiteTimer">
                        <div class="timer-label">白方</div>
                        <div class="timer-value" id="whiteTime">00:00</div>
                    </div>
                </div>
            </div>
            
            <div class="game-controls">
                <button id="undoBtn" class="undo-btn" onclick="requestUndo()" style="margin-bottom: 10px;">悔棋（剩余<span id="undoCount">2</span>次）</button>
                <button class="surrender-btn" onclick="surrender()">认输</button>
            </div>
            
            <div class="game-rules">
                <div class="rules-title">游戏规则</div>
                <div class="rules-content">
                    黑白双方轮流落子，先在横、竖或斜方向上形成连续五子的一方获胜。<br>
                    当棋盘空间为空，未分出胜负则平局处理。
                </div>
            </div>
            
            <div id="reconnectStatus" class="reconnect-status" style="display: none;">
                <div class="reconnect-text">正在重连...</div>
                <div class="reconnect-spinner"></div>
            </div>
            
            <div class="score-preview">
                <div class="score-title">积分变化预览</div>
                <div class="score-item">
                    <span>获胜方</span>
                    <span class="score-positive">+5</span>
                </div>
                <div class="score-item">
                    <span>失败方</span>
                    <span class="score-negative">-3</span>
                </div>
            </div>
        </div>
    </div>
    
    <div class="game-overlay" id="gameOverlay">
        <div class="game-result">
            <div class="result-title" id="resultTitle">游戏结束</div>
            <div class="result-message" id="resultMessage">你赢了！</div>
            <div class="score-change">
                <div class="score-change-title">积分变化</div>
                <div class="score-change-item">
                    <span>本局积分变化</span>
                    <span class="score-positive" id="scoreChange">+5</span>
                </div>
            </div>
            <button class="back-to-lobby-btn" onclick="backToLobby()">返回大厅</button>
        </div>
    </div>

    <script>
        let currentPlayer = 'black'; // 'black' 或 'white'
        let gameBoard = [];
        let gameOver = false;
        let blackTime = 0;
        let whiteTime = 0;
        let gameTimer;
        let lastMove = null;
        let humanColor = null; // 'black' 或 'white'
        let aiColor = null;    // 与 humanColor 相反
        let undoCount = 2;     // 剩余悔棋次数
        let undoRequestPending = false; // 是否有待处理的悔棋请求
        let isWaitingUndoResponse = false; // 是否在等待对方响应悔棋请求
        
        // 初始化游戏
        function initGame() {
            // 初始化15x15棋盘
            gameBoard = Array(15).fill().map(() => Array(15).fill(null));
            
            // 创建棋盘格子
            const board = document.getElementById('gameBoard');
            board.innerHTML = '';
            
            for (let row = 0; row < 15; row++) {
                for (let col = 0; col < 15; col++) {
                    const cell = document.createElement('div');
                    cell.className = 'board-cell';
                    cell.dataset.row = row;
                    cell.dataset.col = col;
                    cell.addEventListener('click', () => handleCellClick(row, col));
                    board.appendChild(cell);
                }
            }
            
            // 分配执子颜色
            assignSides();

            // 开始计时
            startTimer();

            // 如果先手不是玩家，则由对手先落子
            if (humanColor !== currentPlayer) {
                setTimeout(simulateOpponentMove, 700);
            }
        }

        // 随机分配玩家与对手执子颜色，并更新UI
        function assignSides() {
            humanColor = Math.random() < 0.5 ? 'black' : 'white';
            aiColor = humanColor === 'black' ? 'white' : 'black';

            const blackNameEl = document.getElementById('blackPlayerName');
            const whiteNameEl = document.getElementById('whitePlayerName');

            blackNameEl.textContent = humanColor === 'black' ? '我方（黑）' : '对手（黑）';
            whiteNameEl.textContent = humanColor === 'white' ? '我方（白）' : '对手（白）';

            updateTurnIndicator();
        }

        // 仅当轮到玩家自己时响应点击
        function handleCellClick(row, col) {
            if (gameOver) return;
            if (currentPlayer !== humanColor) return; // 非玩家回合不允许落子
            makeMove(row, col);

            // 玩家落子后，如未结束，触发对手模拟落子
            if (!gameOver && currentPlayer === aiColor) {
                setTimeout(simulateOpponentMove, 600);
            }
        }

        // 对手（AI）模拟落子：简单策略为随机选择空位
        function simulateOpponentMove() {
            if (gameOver || currentPlayer !== aiColor) return;
            const empty = getEmptyCells();
            if (empty.length === 0) return;

            // 简单策略：优先在上一步附近，否则随机
            let target = null;
            if (lastMove) {
                const candidates = empty.filter(({row, col}) => Math.abs(row - lastMove.row) <= 1 && Math.abs(col - lastMove.col) <= 1);
                if (candidates.length > 0) {
                    target = candidates[Math.floor(Math.random() * candidates.length)];
                }
            }
            if (!target) {
                target = empty[Math.floor(Math.random() * empty.length)];
            }
            makeMove(target.row, target.col);
        }

        function getEmptyCells() {
            const list = [];
            for (let r = 0; r < 15; r++) {
                for (let c = 0; c < 15; c++) {
                    if (gameBoard[r][c] === null) list.push({row: r, col: c});
                }
            }
            return list;
        }
        
        function makeMove(row, col) {
            if (gameOver || gameBoard[row][col] !== null) return;
            
            // 落子
            gameBoard[row][col] = currentPlayer;
            
            // 创建棋子元素
            const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
            const piece = document.createElement('div');
            piece.className = `piece ${currentPlayer}`;
            cell.appendChild(piece);
            cell.classList.add('occupied');
            
            // 移除上一个最后落子的标记
            if (lastMove) {
                const lastCell = document.querySelector(`[data-row="${lastMove.row}"][data-col="${lastMove.col}"]`);
                const lastPiece = lastCell.querySelector('.piece');
                lastPiece.classList.remove('last-move');
            }
            
            // 标记当前落子
            piece.classList.add('last-move');
            lastMove = { row, col };
            
            // 检查是否获胜
            if (checkWin(row, col)) {
                gameOver = true;
                showGameResult(currentPlayer);
                return;
            }
            
            // 检查是否平局
            if (isBoardFull()) {
                gameOver = true;
                showGameResult('draw');
                return;
            }
            
            // 切换玩家
            currentPlayer = currentPlayer === 'black' ? 'white' : 'black';
            updateTurnIndicator();
            
            // 如果对方发起悔棋请求，显示确认弹窗（模拟）
            if (Math.random() < 0.1) { // 10%概率模拟对方发起悔棋
                setTimeout(simulateOpponentUndoRequest, 1000);
            }
        }
        
        function checkWin(row, col) {
            const directions = [
                [0, 1],   // 水平
                [1, 0],   // 垂直
                [1, 1],   // 对角线
                [1, -1]   // 反对角线
            ];
            
            for (let [dx, dy] of directions) {
                let count = 1;
                const winningPieces = [{row, col}];
                
                // 向一个方向检查
                for (let i = 1; i < 5; i++) {
                    const newRow = row + i * dx;
                    const newCol = col + i * dy;
                    if (isValidPosition(newRow, newCol) && gameBoard[newRow][newCol] === currentPlayer) {
                        count++;
                        winningPieces.push({row: newRow, col: newCol});
                    } else {
                        break;
                    }
                }
                
                // 向相反方向检查
                for (let i = 1; i < 5; i++) {
                    const newRow = row - i * dx;
                    const newCol = col - i * dy;
                    if (isValidPosition(newRow, newCol) && gameBoard[newRow][newCol] === currentPlayer) {
                        count++;
                        winningPieces.push({row: newRow, col: newCol});
                    } else {
                        break;
                    }
                }
                
                if (count >= 5) {
                    // 高亮获胜棋子
                    winningPieces.forEach(({row, col}) => {
                        const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
                        const piece = cell.querySelector('.piece');
                        piece.classList.add('winning');
                    });
                    return true;
                }
            }
            
            return false;
        }
        
        function isValidPosition(row, col) {
            return row >= 0 && row < 15 && col >= 0 && col < 15;
        }
        
        function isBoardFull() {
            return gameBoard.every(row => row.every(cell => cell !== null));
        }
        
        function updateTurnIndicator() {
            const indicator = document.getElementById('turnIndicator');
            const blackPlayer = document.getElementById('blackPlayer');
            const whitePlayer = document.getElementById('whitePlayer');
            
            if (currentPlayer === 'black') {
                indicator.textContent = '轮到黑方';
                blackPlayer.classList.add('current-turn');
                whitePlayer.classList.remove('current-turn');
            } else {
                indicator.textContent = '轮到白方';
                whitePlayer.classList.add('current-turn');
                blackPlayer.classList.remove('current-turn');
            }
        }
        
        function startTimer() {
            gameTimer = setInterval(() => {
                if (currentPlayer === 'black') {
                    blackTime++;
                } else {
                    whiteTime++;
                }
                updateTimerDisplay();
            }, 1000);
        }
        
        function updateTimerDisplay() {
            const blackTimerEl = document.getElementById('blackTimer');
            const whiteTimerEl = document.getElementById('whiteTimer');
            const blackTimeEl = document.getElementById('blackTime');
            const whiteTimeEl = document.getElementById('whiteTime');
            
            // 计算剩余时间（假设每方5分钟，即300秒）
            const totalTime = 300;
            const blackRemaining = totalTime - blackTime;
            const whiteRemaining = totalTime - whiteTime;
            
            blackTimeEl.textContent = formatTime(blackRemaining);
            whiteTimeEl.textContent = formatTime(whiteRemaining);
            
            // 剩余30秒时显示红色警告
            if (currentPlayer === 'black' && blackRemaining <= 30) {
                blackTimerEl.classList.add('warning');
            } else {
                blackTimerEl.classList.remove('warning');
            }
            
            if (currentPlayer === 'white' && whiteRemaining <= 30) {
                whiteTimerEl.classList.add('warning');
            } else {
                whiteTimerEl.classList.remove('warning');
            }
            
            // 时间耗尽自动判负
            if (blackRemaining <= 0 && currentPlayer === 'black') {
                gameOver = true;
                clearInterval(gameTimer);
                showGameResult('white');
            } else if (whiteRemaining <= 0 && currentPlayer === 'white') {
                gameOver = true;
                clearInterval(gameTimer);
                showGameResult('black');
            }
        }
        
        function formatTime(seconds) {
            const minutes = Math.floor(seconds / 60);
            const secs = seconds % 60;
            return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
        }
        
        function showGameResult(result) {
            clearInterval(gameTimer);
            
            const overlay = document.getElementById('gameOverlay');
            const title = document.getElementById('resultTitle');
            const message = document.getElementById('resultMessage');
            const scoreChange = document.getElementById('scoreChange');
            
            if (result === 'draw') {
                // 平局
                title.textContent = '游戏结束';
                title.className = 'result-title result-draw';
                message.textContent = '平局！';
                scoreChange.textContent = '+0';
                scoreChange.className = '';
            } else if (result === humanColor) {
                // 玩家获胜
                title.textContent = '游戏结束';
                title.className = 'result-title result-win';
                message.textContent = '你赢了！';
                scoreChange.textContent = '+5';
                scoreChange.className = 'score-positive';
            } else {
                // 玩家失败
                title.textContent = '游戏结束';
                title.className = 'result-title result-lose';
                message.textContent = '你输了！';
                scoreChange.textContent = '-3';
                scoreChange.className = 'score-negative';
            }
            
            overlay.classList.add('show');
        }
        
        function surrender() {
            if (confirm('确定要认输吗？')) {
                gameOver = true;
                clearInterval(gameTimer);
                // 玩家认输，对手获胜
                const opponentColor = humanColor === 'black' ? 'white' : 'black';
                showGameResult(opponentColor);
            }
        }
        
        function backToLobby() {
            if (confirm('确定要返回游戏大厅吗？当前游戏将被保存。')) {
                window.location.href = 'lobby.html';
            }
        }
        
        // 断线重连功能
        function checkReconnect() {
            // 模拟检测未完成对局
            const hasUnfinishedGame = false; // 实际应从后端获取
            if (hasUnfinishedGame) {
                showReconnectDialog();
            }
        }
        
        function showReconnectDialog() {
            const dialog = document.createElement('div');
            dialog.className = 'game-overlay';
            dialog.style.display = 'flex';
            dialog.innerHTML = `
                <div class="game-result">
                    <div style="font-size: 48px; margin-bottom: 20px;">⚠️</div>
                    <div class="result-title">检测到未完成的对局</div>
                    <div class="result-message">是否重新连接？</div>
                    <div style="margin: 20px 0; padding: 15px; background: #f8f9fa; border-radius: 8px;">
                        <div style="font-size: 12px; color: #7f8c8d;">对手: 玩家002</div>
                        <div style="font-size: 12px; color: #7f8c8d;">对局时间: 2024-01-15 14:30</div>
                    </div>
                    <div style="display: flex; gap: 10px; justify-content: center;">
                        <button class="back-to-lobby-btn" onclick="reconnect()" style="background: #3498db;">重新连接</button>
                        <button class="back-to-lobby-btn" onclick="cancelReconnect()" style="background: #95a5a6;">取消</button>
                    </div>
                </div>
            `;
            document.body.appendChild(dialog);
        }
        
        function reconnect() {
            const overlay = document.querySelector('.game-overlay');
            if (overlay) overlay.remove();
            document.getElementById('reconnectStatus').style.display = 'flex';
            // 模拟重连过程
            setTimeout(() => {
                document.getElementById('reconnectStatus').style.display = 'none';
                // 实际应恢复游戏状态
            }, 2000);
        }
        
        function cancelReconnect() {
            const overlay = document.querySelector('.game-overlay');
            if (overlay) overlay.remove();
        }
        
        // 悔棋功能
        function requestUndo() {
            if (undoCount <= 0) {
                alert('悔棋次数已用完');
                return;
            }
            
            if (isWaitingUndoResponse) {
                alert('悔棋请求已发送，等待对方确认...');
                return;
            }
            
            // 显示悔棋请求弹窗（发起方）
            showUndoRequestDialog();
        }
        
        function showUndoRequestDialog() {
            const dialog = document.createElement('div');
            dialog.className = 'game-overlay';
            dialog.style.display = 'flex';
            dialog.innerHTML = `
                <div class="game-result">
                    <div class="result-title">悔棋请求</div>
                    <div class="result-message">已发送悔棋请求，等待对方确认...</div>
                    <div style="margin: 20px 0;">
                        <button class="back-to-lobby-btn" onclick="cancelUndoRequest()" style="background: #95a5a6;">取消请求</button>
                    </div>
                </div>
            `;
            dialog.id = 'undoRequestDialog';
            document.body.appendChild(dialog);
            isWaitingUndoResponse = true;
            
            // 模拟对方响应（实际应由WebSocket接收）
            setTimeout(() => {
                if (isWaitingUndoResponse && Math.random() < 0.5) {
                    // 模拟对方同意
                    cancelUndoRequest();
                    acceptUndo();
                } else if (isWaitingUndoResponse) {
                    // 模拟对方拒绝
                    cancelUndoRequest();
                    rejectUndo();
                }
            }, 3000);
        }
        
        function cancelUndoRequest() {
            const dialog = document.getElementById('undoRequestDialog');
            if (dialog) dialog.remove();
            isWaitingUndoResponse = false;
        }
        
        // 显示接收方的悔棋确认弹窗（模拟对方发起悔棋请求）
        function showUndoConfirmDialog() {
            const dialog = document.createElement('div');
            dialog.className = 'game-overlay';
            dialog.style.display = 'flex';
            dialog.innerHTML = `
                <div class="game-result">
                    <div class="result-title">悔棋请求</div>
                    <div class="result-message">对方请求悔棋，是否同意？</div>
                    <div style="margin: 20px 0; padding: 15px; background: #f8f9fa; border-radius: 8px;">
                        <div style="font-size: 12px; color: #7f8c8d;">当前棋盘状态预览</div>
                        <div style="font-size: 12px; color: #7f8c8d; margin-top: 10px;">已落子: ${gameBoard.flat().filter(cell => cell !== null).length} 个</div>
                    </div>
                    <div style="display: flex; gap: 10px; justify-content: center;">
                        <button class="back-to-lobby-btn" onclick="acceptUndo()" style="background: #27ae60;">同意</button>
                        <button class="back-to-lobby-btn" onclick="rejectUndo()" style="background: #e74c3c;">拒绝</button>
                    </div>
                </div>
            `;
            dialog.id = 'undoConfirmDialog';
            document.body.appendChild(dialog);
        }
        
        function acceptUndo() {
            const dialog = document.getElementById('undoConfirmDialog');
            if (dialog) dialog.remove();
            
            // 回退到上一步
            if (lastMove) {
                const { row, col } = lastMove;
                gameBoard[row][col] = null;
                
                // 移除棋子
                const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
                const piece = cell.querySelector('.piece');
                if (piece) {
                    piece.remove();
                }
                cell.classList.remove('occupied');
                
                // 切换玩家
                currentPlayer = currentPlayer === 'black' ? 'white' : 'black';
                updateTurnIndicator();
                
                // 更新最后落子位置
                const moves = [];
                for (let r = 0; r < 15; r++) {
                    for (let c = 0; c < 15; c++) {
                        if (gameBoard[r][c] !== null) {
                            moves.push({ row: r, col: c, player: gameBoard[r][c] });
                        }
                    }
                }
                if (moves.length > 0) {
                    lastMove = moves[moves.length - 1];
                    const lastCell = document.querySelector(`[data-row="${lastMove.row}"][data-col="${lastMove.col}"]`);
                    const lastPiece = lastCell.querySelector('.piece');
                    if (lastPiece) {
                        lastPiece.classList.add('last-move');
                    }
                } else {
                    lastMove = null;
                }
                
                // 减少悔棋次数（双方都减少）
                undoCount = Math.max(0, undoCount - 1);
                updateUndoButton();
                
                alert('悔棋成功！');
            }
        }
        
        function updateUndoButton() {
            const undoBtn = document.getElementById('undoBtn');
            const undoCountSpan = document.getElementById('undoCount');
            undoCountSpan.textContent = undoCount;
            
            if (undoCount <= 0) {
                undoBtn.disabled = true;
                undoBtn.textContent = '悔棋（剩余0次）';
            } else {
                undoBtn.disabled = false;
                undoBtn.innerHTML = `悔棋（剩余<span id="undoCount">${undoCount}</span>次）`;
            }
        }
        
        function rejectUndo() {
            const dialog = document.getElementById('undoConfirmDialog');
            if (dialog) dialog.remove();
            alert('对方拒绝了悔棋请求');
        }
        
        // 模拟对方发起悔棋请求（用于测试，实际应由WebSocket接收）
        function simulateOpponentUndoRequest() {
            // 取消注释下面这行来测试悔棋功能
            // showUndoConfirmDialog();
        }
        
        // 页面加载时初始化游戏
        document.addEventListener('DOMContentLoaded', function() {
            initGame();
            updateTurnIndicator();
            updateUndoButton();
            checkReconnect();
        });
    </script>
</body>
</html>
